package handler

import (
	"app-mart-manage/cache"
	"app-mart-manage/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func AddGame(c *gin.Context) {
	name := c.PostForm("name")
	people := c.PostForm("people")
	num := c.PostForm("num")
	data := model.Game{
		Name:   name,
		People: people,
		Num:    num,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	var game model.Game
	redis_key := "game_add" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Debug().Find(&game)
	jsonData, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func GameList(c *gin.Context) {
	var game []model.Game
	err := model.DB.Find(&game).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "game_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&game).Debug()
		jsonData, _ := json.Marshal(game)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &game)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}
func GameDetail(c *gin.Context) {
	id := c.Query("id")
	var game model.Game
	err := model.DB.Find(&game).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "game_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&game).Debug()
		jsonData, _ := json.Marshal(game)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &game)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}

func GameXz(c *gin.Context) {
	id := c.Query("id")
	var game model.Game
	err := model.DB.Find(&game).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "game_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&game).Debug()
		jsonData, _ := json.Marshal(game)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &game)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}
